package com.airport.schedule.util;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {


    public static void saveList2CSVFile(List<String[]> list, String savePath)
            throws IOException {
        CsvWriter writer = new CsvWriter(new BufferedWriter(new FileWriter(savePath)), ',');
        for (String[] record : list) {
            writer.writeRecord(record);
        }
        writer.flush();
        writer.close();
    }

    public static List<String[]> readCsvFile(String file) throws IOException {
        CsvReader reader = new CsvReader(file);
        List<String[]> results = new ArrayList<>();
        while(reader.readRecord()) {
            results.add(reader.getValues());
        }
        return results;
    }

    public static Workbook readWorkbook(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream is = new FileInputStream(file);
        Workbook wb = null;
        if(filePath.endsWith("xls")) {
            wb = new HSSFWorkbook(is);
        }else if(filePath.endsWith("xlsx")) {
            wb = new XSSFWorkbook(is);
        }
        return wb;
    }


}
